import React, { useState, useEffect, useRef } from 'react';

import { ListGroup } from "react-bootstrap"
import { Link } from "react-router-dom"

interface Order {
    title: string;
}

export default function List() {

    const [orderList, setItems] = useState<Order[]>([]);
    const [page, setPage] = useState(1);
    const [size, setSize] = useState(10);


    const [loading, setLoading] = useState(false);
    const containerRef = useRef(null);

    const randomString = (e: number) => {
        e = e || 32;
        const t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
        let a = t.length;
        let n = "";
        for (let i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));

        return n
    }

    const fetchData = async () => {
        setLoading(true);

        let data: any = [];
        for (let i = 0; i < size; i++) {
            data.push({ title: randomString(16) })
        }
        setItems(prevOrders => [...prevOrders, ...data]);
        setPage(prevPage => prevPage + 1);
        setLoading(false);
    };



    useEffect(() => {
        fetchData();
    }, []);

    const handleScroll = () => {
        const container = containerRef.current;
        if (!container) return;

        const { scrollTop, scrollHeight, clientHeight } = container;
        if (scrollHeight - scrollTop === clientHeight) {
            fetchData();
        }
    };

    useEffect(() => {
        const container = containerRef.current as any;
        if (container) {
            container.addEventListener('scroll', handleScroll);
        }
        return () => {
            if (container) {
                container.removeEventListener('scroll', handleScroll);
            }
        };
    }, []);

    return (<div className="App">
        <header className="App-header">
            <h1>Order List (infinite loading)</h1>

            <ListGroup ref={containerRef}
                style={{ height: '350px', width: '300px', overflowY: 'auto', border: '1px solid #ccc' }}>
                {orderList.map((item: { title: string }, index) => <ListGroup.Item key={index + 1}>
                    <Link to={`/product/${index + 1}`}>{item.title}</Link>
                </ListGroup.Item>)}
            </ListGroup>
            {loading ? 'loading...' : ''}
        </header>
    </div>)
}